import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from "@/apis/user";
import { mergeCartAPI } from "@/apis/cart";
import { useCartStore } from './cartStore';

export const useUserStore = defineStore('user', () => {
    let cartStore = useCartStore()
    let userInfo = ref({})
    // 登录获取用户信息
    let getUserInfo = async ({account, password}) => {
        let res = await loginAPI({ account, password })
        userInfo.value = res.result
        // 登录时合并购物车
        let dataArr = cartStore.cartList.map(item => {
            return{
                skuId: item.skuId,
                selected: item.selected,
                conut: item.conut
            }
        })
        await mergeCartAPI(dataArr)
        // 请求接口获取最新的购物车数据
        cartStore.updateNewList()
    }

    // 退出时清除用户数据 和 购物车数据
    let clearUserInfo = () => {
        // pinia-plugin-persistedstate 插件会使pinia和浏览器缓存同步，所以修改pinia就可以了
        userInfo.value = {}
        cartStore.clearCart()
    }

    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
}, {
    // pinia持久化存储插件pinia-plugin-persistedstate配置项
    persist: true
})
